
using System;
using System.IO;
//using System.Net;
using Gtk;

namespace wc_gui_input
{
	
	public class edit_page : Gtk.Window
	{
		protected Gtk.Entry entry_title;
		protected Gtk.TextView text_content;
		protected Gtk.Button but_save;
		protected Gtk.Button but_cancel;
		protected Gtk.Entry entry_pic;
		protected Gtk.Button but_remove0;
		protected Gtk.VBox vbox1;
		//protected Gtk.ScrolledWindow scrolledwindow1;// for html
		
		bool new_page;// whether page being edited is a newly added page
		string page;// filename of page
		string title;// title of page
		string category;// category that page belongs to
		int category_num;// category menu number
		int location;// where new page inserts to in category
		
		bool sound;// does page contain sound, not implemented yet
		string sound_file;// filename of sound
		string old_content;// content saved before edits, will add revert button
		
		bool removed_pic;// flag for if the user wants to delete the picture on save
		
		//protected HTML html;// for WYSIWYG editor
		
		public edit_page(string filename, string page_title, int loc, bool modify, string cat, int cat_num) : 
				base("")
		{
			// filename=page filename, empty if new
			// page_title=title of page, empty if new
			// cat=category filename
			// loc=location of page, empty if existing

			Stetic.Gui.Build(this, typeof(wc_gui_input.edit_page));
			new_page=!modify;
			page=filename;
			title=page_title;
			entry_title.Text=title;
			category=cat;
			category_num=cat_num;
			location=loc;
			
			removed_pic=false;// assume user wants to keep picture
			
			// WYSIWYG editor for future
			/*
			html = new HTML ();
			scrolledwindow1.Add (html);
			LoadHtml("http://www.google.com");
			*/

			if (modify == true) {
				// not a new page
				init_widgets();
			}
		}
/*		// WYSIWYG editor function
		void LoadHtml (string URL)
                {
                        HttpWebRequest web_request = (HttpWebRequest) WebRequest.Create (URL);
                        HttpWebResponse web_response = (HttpWebResponse) web_request.GetResponse ();
               Stream stream = web_response.GetResponseStream ();
               byte [] buffer = new byte [8192];
               
               HTMLStream html_stream = html.Begin ();
               int count;
               
               while ((count = stream.Read (buffer, 0, 8192)) != 0){
                    html_stream.Write (buffer, count);
               }
               //html.End (html_stream, HTMLStreamStatus.Ok);
                }
*/		
		
		protected virtual void init_widgets() {
			TextReader infile;// infile is page ( category --> page )
			try {
	 			infile = new StreamReader(page); // file to read from 
	    	} catch(FileNotFoundException exc) { 
	      		Console.WriteLine(exc.Message); 
	   	   		return; 
    		}
    		
    		String line;
			text_content.Buffer.Clear();
			sound=false;// initialize whether page has sound
			
			while (infile.Peek() != -1) { // parse html
				line=infile.ReadLine();
				if (line=="<!-- CONTENT -->") { 
				// this is the line before the line with the content
					line=infile.ReadLine();// get to line with content
					
					// test for picture
					if (line.StartsWith("<img")) {
						// put img filename in entry_pic & avoid inputting into text_content.Buffer
						entry_pic.Text=line.Substring(line.IndexOf("src=")+5,line.IndexOf(">")-1-(line.IndexOf("src=")+5));
						line=line.Substring(line.IndexOf(">")+1, line.Length-line.IndexOf(">")-1);
					}					
					text_content.Buffer.Text=line;
					old_content=line;
					// test for sound, on next line
					line=infile.ReadLine();
					if (line!="<!-- SOUND -->") {
						sound=true;
						//sound_file=line.Substring();// need to implement
					}
					break;
				}
			}
			infile.Close();
		}

		protected virtual void OnButCancelClicked(object sender, System.EventArgs e)
		{
			this.Destroy();
			return;
		}

		// PREREQ: User clicked save
		// RESULT: writes to file
		// NOTES:  if page is new, reads from template.html
		protected virtual void OnButSaveClicked(object sender, System.EventArgs e)
		{
			String page_read=page;// reading from this
			
			// Insert picture if being used
			if (entry_pic.Text.Trim() != "") {
				// copy picture to local data
				string pic_filename=entry_pic.Text.Trim();
				try {
					if (pic_filename.LastIndexOf("/") != -1)
						pic_filename = pic_filename.Substring(pic_filename.LastIndexOf("/")+1, pic_filename.Length-pic_filename.LastIndexOf("/")-1);
		 			// in order to make sure multiple pictures with the same filename
		 			// can be added, prepend with filename-".html"
		 			pic_filename=pic_filename.Insert(0,page.Substring(0,page.IndexOf("."))+"_");
		 			
		 			File.Copy(entry_pic.Text.Trim(),pic_filename); // file to read from
		    	} catch(FileNotFoundException exc) { 
		      		MessageDialog md = new MessageDialog (this,
									DialogFlags.DestroyWithParent,
                                   MessageType.Error, 
                                      ButtonsType.Close, "Picture file not found!");     
					int result = md.Run ();
					md.Destroy();
					Console.WriteLine(exc.Message); 
		      		return;
		    	}
				text_content.Buffer.Text = text_content.Buffer.Text.Insert(0,"<img style=\"float: right;\" hspace=\"10\" src=\""+pic_filename+"\">");
			}
			
			if (removed_pic) {
				// user wants to remove pic
				try {
		 			File.Delete(entry_pic.Text); 
		    	} catch(FileNotFoundException exc) { 
		      		Console.WriteLine(exc.Message); 
		      		return; 
		    	}
	    	}
			
			TextReader infile;// infile is page ( category --> page )
			
			// if new page being created, read from template
			if (new_page == true) {
				page_read="template.html";
			}
			
			try {
	 			infile = new StreamReader(page_read); // file to read from 
	    	} catch(FileNotFoundException exc) { 
	      		Console.WriteLine(exc.Message); 
	      		return; 
	    	}	    	

			FileStream outfile; // file to write to
			try {
				outfile = new FileStream(page+".backup", FileMode.OpenOrCreate, FileAccess.Write);
			} catch(UnauthorizedAccessException exc) {
				Console.WriteLine(exc.Message);
				return;
			}
			
			// Create a new stream to write to the file
			StreamWriter sw = new StreamWriter(outfile);

	        int line_count = 0;
	        while (infile.Peek() != -1) { // reading file to write in formatted html to file
				String temp = infile.ReadLine();
				if (temp=="<!-- CONTENT -->") { 
				// this is the line before the line with the content
					sw.WriteLine(temp);// keep flag in new/edited file
					temp = infile.ReadLine();// get to line with content
					line_count++;// account for above
					sw.WriteLine(text_content.Buffer.Text);// writing the new content
				} else {
				// write other html
					// if new page, replace template keywords with actual data
					if (new_page == true) {
						temp=temp.Replace("<!-- CATEGORY -->", category);
						temp=temp.Replace("<!-- TITLE -->",title);
						temp=temp.Replace("<!-- CATEGORY NUMBER -->",category_num.ToString());
						sw.WriteLine(temp);
					} else {
						// not a new page, just copy line for line
						sw.WriteLine(temp);
					}
				}
				line_count++;// increase # to append next template text file
			}
			infile.Close();
			sw.Close();
			outfile.Close();

			if (new_page == true) {
				insert_page_into_category();
			} else {
				File.Delete(page);// delete old page
			}
			File.Move(page+".backup",page);
			this.Destroy();
			return;
		}

		protected virtual void OnButRemove0Clicked(object sender, System.EventArgs e)
		{	
			removed_pic=true;
			entry_pic.Text="";
		}

/*		// PREREQ:  none
		// RESULT:  adds picture to page
		protected virtual void OnButBrowse0Clicked(object sender, System.EventArgs e)
		{
			img_0.File=browse_picture();
		}
*/		
		// PREREQ:  new page saved
		// RESULT:  inserts page into category db file in correct location
		protected virtual void insert_page_into_category(){
			TextReader infile;// infile is category
			String cat_filename="cat_"+page.Substring(0,6)+".txt";
			
			try {
	 			infile = new StreamReader(cat_filename); // file to read from 
	    	} catch(FileNotFoundException exc) {
	      		Console.WriteLine(exc.Message);
	      		return;
	    	}

			FileStream outfile; // file to write to
			try {
				outfile = new FileStream(cat_filename+".backup", FileMode.OpenOrCreate, FileAccess.Write);
			} catch(UnauthorizedAccessException exc) {
				Console.WriteLine(exc.Message);
				return;
			}
			
			// Create a new stream to write to the file
			StreamWriter sw = new StreamWriter(outfile);

	        int line_count = 0;
	        while (infile.Peek() != -1) { // reading file to write in formatted html to file
				String line = infile.ReadLine();
				if (line_count == location) {
					// writing the new content
					sw.WriteLine(page+" "+title);
				}
				sw.WriteLine(line);
				line_count++;// increase # to append next template text file
				
				// test whether location is last category
				if ((line_count == location) && (infile.Peek() == -1)) {
					// writing the new content
					sw.WriteLine(page+" "+title);
				}
			}
			infile.Close();
			sw.Close();
			outfile.Close();

			File.Delete(cat_filename);
			File.Move(cat_filename+".backup",cat_filename);
			
			// now insert page correctly into dynamic.js
			try {
	 			infile = new StreamReader("dynamic.js"); // file to read from 
	    	} catch(FileNotFoundException exc) {
	      		Console.WriteLine(exc.Message);
	      		return;
	    	}

			try {
				outfile = new FileStream("dynamic.js.backup", FileMode.OpenOrCreate, FileAccess.Write);
			} catch(UnauthorizedAccessException exc) {
				Console.WriteLine(exc.Message);
				return;
			}
			
			// Create a new stream to write to the file
			sw = new StreamWriter(outfile);

	        while (infile.Peek() != -1) { // reading file to write in formatted html to file
				String line = infile.ReadLine();
				if (line.IndexOf("<ul id=\"subnav-"+category_num+"\">")!=-1) {
					// page's category, let's put the page in order
					// we want to write the first line no matter what because
					// it contains the above line.  So we'll test for "<="
					for (int i=0; i<=location; i++) {
						sw.WriteLine(line);
						line=infile.ReadLine();
					}
					// now we are at the right page order, let's write the new content
					sw.WriteLine("document.writeln('      <li><a href=\""+page+"\">"+title+"</a></li>');");
				}
				sw.WriteLine(line);
			}
			infile.Close();
			sw.Close();
			outfile.Close();

			File.Delete("dynamic.js");
			File.Move("dynamic.js.backup","dynamic.js");			
		}

	}
}
